package com.lession.filter;

import com.alibaba.fastjson.JSONObject;
import com.lession.common.Ret;
import com.lession.common.RetEnum;
import com.lession.config.AuthRepository;
import org.apache.commons.io.Charsets;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.Ordered;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Enumeration;

@WebFilter(urlPatterns = "*", filterName = "permitFilter")
public class PermitFilter implements Filter, Ordered {
	@Autowired
	public AuthRepository authRepository;
	
	@Override
	public void init(FilterConfig filterConfig) {
	
	}
	
	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		String uri = request.getRequestURI();
		System.err.println(uri+":"+request.getHeader("token"));
		if (uri.startsWith("/login/nverify")
				||uri.startsWith("/ai")
				||uri.startsWith("/lesson")
//				||uri.startsWith("/user")
				|| uri.startsWith("/static") || uri.startsWith("/js") || uri.startsWith("/scss")) {// 后台生成静态封面需要的静态资源目录
			filterChain.doFilter(servletRequest, servletResponse);
		} else if (uri.startsWith("/login/verificate")) {// 统一登录
			ResponseWrapper wrapperResponse = new ResponseWrapper((HttpServletResponse) servletResponse);//转换成代理类
			filterChain.doFilter(servletRequest, wrapperResponse);
			byte[] content = wrapperResponse.getContent();//获取返回值
			//判断是否有值
			if (content.length > 0) {
				JSONObject result = JSONObject.parseObject(new String(content, Charsets.UTF_8));
				if (result.get("code").equals(RetEnum.OPERATE_SUCCESS_INFO.getCode())) {
					// 登录成功保存token
					String token = authRepository.save(result.getJSONObject("data").getString("userId"));
					((HttpServletResponse) servletResponse).setHeader("token", token);
					((HttpServletResponse) servletResponse).setHeader("Access-Control-Expose-Headers", "token,Content-Disposition,File-Name");
				}
				ServletOutputStream out = servletResponse.getOutputStream();
				out.write(content);
				out.flush();
			}
		} else {
			String token = request.getHeader("token");//获取token
			if (!StringUtils.isBlank(token) && authRepository.isPermitted(token) || uri.indexOf("/webSocket") != -1) {
				filterChain.doFilter(servletRequest, servletResponse);
				((HttpServletResponse) servletResponse).setHeader("token", token);
				((HttpServletResponse) servletResponse).setHeader("Access-Control-Expose-Headers", "token,Content-Disposition,File-Name");
			} else {
				ServletOutputStream out = servletResponse.getOutputStream();
				String str = Ret.error(RetEnum.LOGIN_AUTH_1003.getCode()).build().toString();
				out.write(str.getBytes());
				out.flush();
			}
		}
		
	}
	
	@Override
	public void destroy() {
	
	}
	
	@Override
	public int getOrder() {
		return -1;
	}
	
}
